package com.yj.auto.component.base.controller;

import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Page;
import com.yj.auto.Constants;
import com.yj.auto.component.base.model.Notice;
import com.yj.auto.component.base.service.NoticeService;
import com.yj.auto.core.base.annotation.Controller;
import com.yj.auto.core.base.annotation.Valid;
import com.yj.auto.core.base.model.QueryModel;
import com.yj.auto.core.base.model.ResponseModel;
import com.yj.auto.core.jfinal.base.BaseController;
import com.yj.auto.helper.LogHelper;
import com.yj.auto.plugin.table.model.DataTables;
import com.yj.auto.utils.DateUtil;

/**
 * 通知公告 管理
 * 
 * 描述：
 * 
 */
@Controller(viewPath = "component/base")
public class NoticeController extends BaseController {
	private static final Log logger = Log.getLog(NoticeController.class);

	private static final String RESOURCE_URI = "notice/index";
	private static final String INDEX_PAGE = "notice_index.html";
	private static final String FORM_PAGE = "notice_form.html";
	private static final String SHOW_PAGE = "notice_show.html";

	NoticeService noticeSrv = null;

	public void index() {
		QueryModel query = new QueryModel();
		query.setStime(DateUtil.toDateStr(DateUtil.addDay(DateUtil.date(), -7)));
		setAttr("query", query);
		render(INDEX_PAGE);
	}

	public void list(QueryModel query) {
		DataTables<Notice> dt = getDataTable(query, noticeSrv);
		renderJson(dt);
	}

	// 首页展示未读的的公告
	public void portlet() {
		QueryModel query = new QueryModel();
		query.setUserId(getSuId());
		query.setState(Constants.DATA_STATE_VALID);
		Page<Notice> page = noticeSrv.paginate(query);
		renderJson(page);
	}

	public void get() {
		Integer id = getParaToInt(0);
		Notice model = noticeSrv.get(id);
		setAttr("model", model);
		LogHelper.addReadingLog(getSuId(), id, model.getTableName());// 添加阅读记录
		render(SHOW_PAGE);
	}

	public void form() {
		Integer id = getParaToInt(0);
		Notice model = null;
		if (null != id && 0 != id) {
			model = noticeSrv.get(id);
		} else {
			model = new Notice();
		}
		setAttr("model", model);
		render(FORM_PAGE);
	}

	@Valid(type = Notice.class)
	public boolean saveOrUpdate(Notice model) {
		model.setLuser(getSuId());
		model.setLtime(Constants.NOW());
		initAttaMap(model, NoticeService.ATTA_NOTICE);// 公告附件
		boolean success = false;
		if (null == model.getId()) {
			success = noticeSrv.save(model);
		} else {
			success = noticeSrv.update(model);
		}
		ResponseModel<String> res = renderSaveOrUpdate(success, noticeSrv);
		return res.isSuccess();
	}

	public boolean delete() {
		ResponseModel<String> res = _delete(noticeSrv);
		return res.isSuccess();
	}
}